package i.i.myapplication.view;

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import i.i.myapplication.R;
import androidx.annotation.Nullable;

//package i.i.myapplication.view;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import i.i.myapplication.model.Music;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class MusicDetailActivity extends AppCompatActivity {

    private ImageView ivMusic, btnPlay, btnPause, btnPre, btnNext, btnExit;
    private TextView songName, artistName, tvProgress, tvTotal;
    private SeekBar seekBar;

    private MusicService.MusicControl musicControl;
    private ServiceConnection connection;

    private List<Music> musicList = new ArrayList<>();
    private int currentPosition;

    private Handler handler = new Handler();

    private Runnable updateProgressRunnable = new Runnable() {
        @Override
        public void run() {
            if (musicControl != null && musicControl.isPlaying()) {
                int progress = musicControl.getCurrentPosition();
                int total = musicControl.getDuration();
                seekBar.setMax(total);
                seekBar.setProgress(progress);
                tvProgress.setText(formatTime(progress));
                tvTotal.setText(formatTime(total));
                handler.postDelayed(this, 1000);
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_detail);

        initView();
        initMusicList(); // 你可改为从全局或者数据库获取列表，演示用这里初始化

        Intent intent = getIntent();
        currentPosition = intent.getIntExtra("position", 0);

        bindMusicService();

        updateUI(currentPosition);

        setListener();
    }

    private void initView() {
        ivMusic = findViewById(R.id.iv_music);
        btnPlay = findViewById(R.id.btn_play);
        btnPause = findViewById(R.id.btn_pause);
        btnPre = findViewById(R.id.btn_pre);
        btnNext = findViewById(R.id.btn_next);
        btnExit = findViewById(R.id.btn_exit);

        songName = findViewById(R.id.song_name);
        artistName = findViewById(R.id.tv_artist);  // 你需要在布局加上这个TextView，显示歌手名
        tvProgress = findViewById(R.id.tv_progress);
        tvTotal = findViewById(R.id.tv_total);
        seekBar = findViewById(R.id.sb);
    }

    // 这里模拟初始化列表，你可以传列表或从数据库加载
    private void initMusicList() {
        musicList.add(new Music(R.drawable.img_01, "Innocence-A R L ", "艾薇儿", R.raw.music1));
        musicList.add(new Music(R.drawable.img_02, "不用去猜-薛之谦", "薛之谦", R.raw.music2));
        musicList.add(new Music(R.drawable.img_03, "不用去猜-Jony J", "Jony J", R.raw.music3));
        musicList.add(new Music(R.drawable.img_04, "一人有一个梦想-黎瑞恩", "黎瑞恩", R.raw.music3));
        // 更多歌曲...
    }

    private void bindMusicService() {
        Intent intent = new Intent(this, MusicService.class);
        connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                musicControl = (MusicService.MusicControl) service;
                playMusic(currentPosition);
                handler.post(updateProgressRunnable);
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                musicControl = null;
            }
        };
        bindService(intent, connection, Context.BIND_AUTO_CREATE);
    }

    private void playMusic(int position) {
        if (musicControl != null) {
            musicControl.play(position + 1); // 你 MusicService 里是从1开始命名
            updateUI(position);
            btnPlay.setVisibility(View.GONE);
            btnPause.setVisibility(View.VISIBLE);
        }
    }

    private void updateUI(int position) {
        Music music = musicList.get(position);
        ivMusic.setImageResource(music.getImageResId());
        songName.setText(music.getName());
        artistName.setText(music.getArtist());

        tvProgress.setText("00:00");
        // 先设置最大值，后续由Runnable更新
        seekBar.setProgress(0);
    }

    private void setListener() {
        btnExit.setOnClickListener(v -> finish());

        btnPlay.setOnClickListener(v -> {
            if (musicControl != null) {
                musicControl.continuePlay();
                btnPlay.setVisibility(View.GONE);
                btnPause.setVisibility(View.VISIBLE);
                handler.post(updateProgressRunnable);
            }
        });

        btnPause.setOnClickListener(v -> {
            if (musicControl != null) {
                musicControl.pausePlay();
                btnPause.setVisibility(View.GONE);
                btnPlay.setVisibility(View.VISIBLE);
            }
        });

        btnPre.setOnClickListener(v -> {
            if (currentPosition > 0) {
                currentPosition--;
                playMusic(currentPosition);
            } else {
                Toast.makeText(this, "已经是第一首", Toast.LENGTH_SHORT).show();
            }
        });

        btnNext.setOnClickListener(v -> {
            if (currentPosition < musicList.size() - 1) {
                currentPosition++;
                playMusic(currentPosition);
            } else {
                Toast.makeText(this, "已经是最后一首", Toast.LENGTH_SHORT).show();
            }
        });

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            boolean fromUser = false;

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean user) {
                fromUser = user;
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // 用户开始拖动时暂停更新进度条，避免冲突
                handler.removeCallbacks(updateProgressRunnable);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (musicControl != null && fromUser) {
                    musicControl.seekTo(seekBar.getProgress());
                    handler.post(updateProgressRunnable);
                }
            }
        });
    }

    private String formatTime(int ms) {
        int totalSeconds = ms / 1000;
        int minutes = totalSeconds / 60;
        int seconds = totalSeconds % 60;
        return String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(updateProgressRunnable);
        if (connection != null) {
            unbindService(connection);
            connection = null;
        }
    }
}

